package sz.szsmk.citizencard.ioc.module;

import android.util.Log;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.GsdxNetApi;
import sz.szsmk.citizencard.model.network.interceptor.HeaderInterceptor;
import sz.szsmk.citizencard.util.Constant;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okio.Buffer;
import okio.BufferedSource;

/**
 * 提供GsdxNetApi对象，通用OkHttpClient在这里配置
 *
 * @author yang12345
 * @time 2017/3/17 下午4:35
 * @mail yangjunyan@xwtec.cn
 */

@Module
public class GsdxNetApiModule {

    @Provides
    public OkHttpClient provideOkHttpClient() {
        if (Constant.IS_TEST_ENVIRONMENT) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .connectTimeout(30 * 1000, TimeUnit.MILLISECONDS)
//                    .addNetworkInterceptor(new StethoInterceptor())
//                    .addInterceptor(new LoggingInterceptor())
                    .addInterceptor(new HeaderInterceptor())
                    .readTimeout(30 * 1000, TimeUnit.MILLISECONDS)
                     //失败重发
                    .retryOnConnectionFailure(true);
            return builder.build();
        } else {
            OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS)
                    .connectTimeout(30 * 1000, TimeUnit.MILLISECONDS)
//                    .addInterceptor(new LoggingInterceptor())
                    .addInterceptor(new HeaderInterceptor())
                    .addInterceptor(provideCacheInterceptor())
                    .cache(provideCache())
                    .readTimeout(30 * 1000, TimeUnit.MILLISECONDS)
                    .retryOnConnectionFailure(true);
            builder.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {

                    okhttp3.Request request = chain.request();
                    okhttp3.Request newRequest = request.newBuilder()
                            .addHeader("Content-Language", "zh-CN")
                            .addHeader("Accept-Language", "zh-CN")
                            .build();
                    okhttp3.Headers headers = request.headers();
                    L.e("request body:" + request.body().toString());
                    L.e("request headers:");
                    Map<String, List<String>> stringListMap = headers.toMultimap();
                    for (Map.Entry<String, List<String>> entry : stringListMap.entrySet()) {
                        List<String> values = entry.getValue();
                        StringBuffer sb = new StringBuffer();
                        for (String value : values) {
                            sb.append(value).append(" ");
                        }
                        L.e("   " + entry.getKey() + "=" + sb.toString());
                    }
                    Response proceed = chain.proceed(newRequest);
                    okhttp3.ResponseBody responseBody = proceed.body();
                    BufferedSource source = responseBody.source();
                    source.request(Long.MAX_VALUE);
                    Buffer buffer = source.buffer();
                    Charset charset = Charset.forName("UTF-8");
                    okhttp3.MediaType contentType = responseBody.contentType();
                    if (contentType != null) {
                        charset = contentType.charset(Charset.forName("UTF-8"));
                    }

                    if (responseBody.contentLength() != 0) {
                        L.e("响应内容:" + buffer.clone().readString(charset));
                    }
                    String host = request.url().host();
//                    CookieHandler.processResponseCookie(proceed,host);
                    return null;
                }
            });

            return builder.build();
        }
    }


    @Singleton
    @Provides
    protected GsdxNetApi provideGsdxNetApi(OkHttpClient okHttpClient) {
        return new GsdxNetApi(okHttpClient);
    }

    //设置缓存目录和缓存空间大小
    private static Cache provideCache() {
        Cache cache = null;
        try {
            cache = new Cache(new File(DaggerApplication.getIns().getCacheDir(), "http-cache"),
                    200 * 1024 * 1024); // 200 MB
        } catch (Exception e) {
            Log.e("cache", "Could not create Cache!");
        }
        return cache;
    }

    public static Interceptor provideCacheInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response response = chain.proceed(chain.request());

                // re-write response header to force use of cache
                CacheControl cacheControl = new CacheControl.Builder()
                        .maxAge(2, TimeUnit.MINUTES)
                        .build();

                return response.newBuilder()
                        .header("Cache-Control", cacheControl.toString())
                        .build();
            }
        };
    }

}
